using System.IO;
using Shinkansen.Core;
using Shinkansen.Runtime;
using Shinkansen.Support;
using Shinkansen.Web.UI.WebControls;

namespace Shinkansen.Model
{
    public class IndividualQueryStringBuilder : IQueryStringBuilder
    {
        private readonly IStaticInclude _resource;
        private readonly PathResolver _pathResolver = new PathResolver ();

        /// <summary>
        /// Initializes a new instance of the <see cref="IndividualQueryStringBuilder"/> class.
        /// </summary>
        /// <param name="resource">The resource.</param>
        public IndividualQueryStringBuilder (IStaticInclude resource)
        {
            _resource = resource;
        }

        /// <summary>
        /// Builds the specified query string.
        /// </summary>
        /// <param name="queryString">The query string.</param>
        public void ConstructQueryString (QueryString queryString)
        {
            string absolutePath = _pathResolver.ToAbsolute (_resource.Path);
            string physicalPath = _pathResolver.ToPhysical (absolutePath);

            if (!File.Exists (physicalPath))
                throw new FileNotFoundException (string.Format ("File '{0}' is not found.", absolutePath));

            long    ticks = File.GetLastWriteTime (physicalPath).Ticks;
            string  timestampHash = new Cryptography ().GenerateMD5Hash (ticks);

            queryString[Tokens.Path] = absolutePath;
            queryString[Tokens.Timestamp] = timestampHash;
        }
    }
}